//
//  HomeTableViewController.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/23.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import SVProgressHUD


class HomeTableViewController: VisitorTableViewController {

    private lazy var statusListViewModel = StatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin {
            visitorView?.setupInfo("关注一些人，回这里看看有什么惊喜", imageName: nil)
            return
        }
        prepareTableView()
        
        loadData()
        loadData()
        
        /// 注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification, object: nil, queue: nil) { [weak self](notification) -> Void in
            
            guard let indexPath = notification.userInfo?[WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                return
            }
            guard let urls = notification.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else {
                return
            }
            
            guard let cell = notification.object as? PhotoBrowerPresentDelegate else {
                return
            }
            let vc = PhotoBrowserViewController(urls: urls, indexPath: indexPath)
            // 设置 modal 的类型是自定义类型
            vc.modalPresentationStyle = .Custom
            // 设置 modal 动画的代理
            vc.transitioningDelegate = self?.photoBrowerAnimator
            
            // 设置 present 的代理
            self?.photoBrowerAnimator.setDelegateParmas(cell, photoBrowerDismissDelegate: vc, indexPath: indexPath)
            self?.presentViewController(vc, animated: true, completion: nil)
        }
    }
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //加载模型数据
    @objc private func loadData() {
        
        refreshControl?.beginRefreshing()
        statusListViewModel.loadStatus(pullupView.isAnimating()) { (isSuccessed) -> () in

            self.refreshControl?.endRefreshing()
            
            self.pullupView.stopAnimating()
            
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("加载数据出错,请稍后")
                return
            }
            self.tableView.reloadData()
        }
    }
    
    //准备表格
    func prepareTableView() {
        tableView.registerClass(StatusNomalCell.self, forCellReuseIdentifier: StatusNomalCellID)
        tableView.registerClass(StatusRetweedCell.self, forCellReuseIdentifier: StatusRetweedCellID)
        tableView.separatorStyle = .None
        tableView.estimatedRowHeight = 400
        
        
         /// 下拉刷新数据
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        // 上拉刷新
        tableView.tableFooterView = pullupView
        
        
        
    }
    
   //MARK: - 懒加载控件
    /// 上拉刷新提示视图
    private lazy var pullupView: UIActivityIndicatorView = {
       let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.orangeColor()
        return indicator
    }()
    
    
    /// 照片查看转场动画代理
    private lazy var photoBrowerAnimator: PhotoBrowerAnimater = PhotoBrowerAnimater()
}

// MARK: - 数据源方法
extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellID = self.statusListViewModel.statusList[indexPath.row].cellID
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! StatusCell
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullupView.isAnimating(){
            pullupView.startAnimating()
            loadData()
            print("上拉刷新")
        }
        
        cell.statusCellDelegate = self
        
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let height = statusListViewModel.statusList[indexPath.row].rowHeight
        
        
        return height
    }
}
extension HomeTableViewController: StatusCellDelegate {
    func labelDidSelectedLinkText(url: NSURL) {
        let vc = HomeWebViewController(url: url)
        vc.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(vc, animated: true)
    }
}
